<template>
  <t-dialog
    :visible="visible"
    :header="modalTitle"
    :width="600"
    :footer="false"
    @close="handleClose"
  >
    <div class="dispatch-form">
      <t-form ref="form" :data="formData" :rules="rules">
        <t-form-item label="调度时间" name="dispatchTime">
          <t-date-picker
            v-model="formData.dispatchTime"
            enable-time-picker
            format="YYYY-MM-DD HH:mm:ss"
          />
        </t-form-item>
        
        <t-form-item label="调度类型" name="dispatchType">
          <t-select v-model="formData.dispatchType" :options="dispatchTypes" />
        </t-form-item>
        
        <t-form-item label="调度说明" name="description">
          <t-textarea
            v-model="formData.description"
            :placeholder="mode === 'single' ? '请输入调度说明' : `请输入调度说明，已选择 ${data.length} 条记录`"
            :maxlength="200"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </t-form-item>

        <div v-if="mode === 'batch'" class="selected-items">
          <div class="selected-header">
            <span>已选择项目</span>
            <span class="selected-count">共 {{ data.length }} 条</span>
          </div>
          <div class="selected-list">
            <div v-for="item in data" :key="item.key" class="selected-item">
              <span>{{ item.region }}</span>
              <span>数量: {{ item.amount }}</span>
            </div>
          </div>
        </div>

        <div v-else class="single-item">
          <div class="item-info">
            <span class="label">派单区域：</span>
            <span>{{ data[0]?.region }}</span>
          </div>
          <div class="item-info">
            <span class="label">数量：</span>
            <span>{{ data[0]?.amount }}</span>
          </div>
        </div>

        <div class="form-footer">
          <t-space>
            <t-button theme="default" @click="handleClose">取消</t-button>
            <t-button theme="primary" :loading="submitting" @click="handleSubmit">
              {{ mode === 'single' ? '确认派单' : '确认批量派单' }}
            </t-button>
          </t-space>
        </div>
      </t-form>
    </div>
  </t-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';

interface DataItem {
  key: string;
  region: string;
  amount: number;
  status: number;
  id?: string;
  name?: string;
}

interface WarningTask {
  warningId: string;
  name: string;
}

const props = defineProps<{
  visible: boolean;
  data: DataItem[];
  mode?: 'single' | 'batch'; // 新增模式属性
}>();

const emit = defineEmits(['update:visible', 'success']);

const form = ref();
const submitting = ref(false);
const formData = ref({
  dispatchTime: null,
  dispatchType: '',
  description: '',
});

// 计算标题
const modalTitle = computed(() => {
  return props.mode === 'single' ? '派单' : '批量派单';
});

const dispatchTypes = [
  { label: '紧急调度', value: 'urgent' },
  { label: '常规调度', value: 'normal' },
  { label: '临时调度', value: 'temporary' },
];

const rules = {
  dispatchTime: [{ required: true, message: '请选择调度时间' }],
  dispatchType: [{ required: true, message: '请选择调度类型' }],
  description: [{ required: true, message: '请输入调度说明' }],
};

const handleClose = () => {
  emit('update:visible', false);
  formData.value = {
    dispatchTime: null,
    dispatchType: '',
    description: '',
  };
};

const handleSubmit = async () => {
  const valid = await form.value.validate();
  if (!valid) return;

  submitting.value = true;
  try {
    // 根据不同模式处理数据
    const warningTasks: WarningTask[] = props.data.map(item => ({
      warningId: item.id || item.key,
      name: item.name || item.region
    }));

    // 这里可以发送API请求
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟成功响应
    MessagePlugin.success(props.mode === 'single' ? '派单成功' : '批量派单成功');
    emit('success', {
      type: props.mode,
      tasks: warningTasks,
      dispatchInfo: { ...formData.value }
    });
    handleClose();
  } catch (error) {
    MessagePlugin.error(props.mode === 'single' ? '派单失败' : '批量派单失败');
  } finally {
    submitting.value = false;
  }
};

// 监听弹窗显示状态
watch(() => props.visible, (val) => {
  if (val && props.data.length > 0) {
    // 如果是单行派单，可以预填一些信息
    if (props.mode === 'single') {
      const item = props.data[0];
      formData.value.description = `派单至${item.region}`;
    }
  }
});
</script>

<style scoped>
.dispatch-form {
  padding: 20px;
}

.selected-items {
  margin: 16px 0;
  border: 1px solid #e7e7e7;
  border-radius: 3px;
}

.selected-header {
  padding: 8px 16px;
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e7e7e7;
}

.selected-count {
  color: #666;
  font-size: 14px;
}

.selected-list {
  max-height: 200px;
  overflow-y: auto;
  padding: 8px 16px;
}

.selected-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.selected-item:last-child {
  border-bottom: none;
}

.form-footer {
  margin-top: 24px;
  text-align: right;
}

.single-item {
  margin-bottom: 16px;
}

.item-info {
  margin-bottom: 8px;
}

.label {
  font-weight: bold;
}
</style> 